# TODO: Add comment
# 
# Author: guochun
###############################################################################



# soil data transformer
soil.tran=function(soil,url){
	library(foreign)
	library(spatstat)
	n=length(soil)
	wd=getwd()
	setwd(url)
	result=list()
	for (i in 1:n){
		da=read.dbf(paste(soil[i],".dbf",sep=""))
		da=matrix(da[,2],nrow=121,ncol=246,byrow=T)
		da=da[sort(1:121,decreasing=T),]
		#if (all(da>0))
		#	da=log(da)
		#else
		#da=log(da-min(da)+1)
		result[[i]]=im(da,xcol=seq(10,990,by=4),yrow=seq(10,490,by=4))
	}
	names(result)=soil
	setwd(wd)
	return(result)
}


#delete rare species

del.rare=function(data,n.rare){
#@ n.rare:	the minimun number of individuals for study species
	n=table(data$sp)
	sp=names(n)
	del=which(n<=n.rare)
	
	for (i in del){
		data=data[-which(data$sp==sp[i]),]
	}
	
	data$sp=as.factor(as.character(data$sp))
	return(data)
}


dister.mk=function(data,plotdim,sigma=4){
	data.ppp=ppp(data$gx,data$gy,window=owin(c(0,plotdim[1]),c(0,plotdim[2])),check=FALSE)
	dister=density(data.ppp,sigma=sigma,dimyx=c(plotdim[2]/sigma,plotdim[1]/sigma))
	return(dister)
}



